import React from 'react';
import {Button, Icon, Row, Col, Spin, message} from 'antd';
import {WeaTools, WeaDialog, WeaBrowser, WeaSelect, WeaInput, WeaDateGroup} from 'ecCom';
import {WeaLocaleProvider} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
import {getSelectedName, DATE_TYPES, getDateTypeName, isMultiBrowserType} from './util/';
import './style/';

class SynergySetting4Designer extends React.Component {
    state = {
        visible: false,
        loading: false,
        settingParams: {},
        paramObj: {},
        compareTypeObj: {},
        valueTypeObj: {},
        paramValueOptions: [],
        paramValueObj: {},
        expsObj: {},
        selectedExps: [],
        selectedExpsPKey: ''
    };

    constructor(props) {
        super(props);
        this.getButtons = this.getButtons.bind(this);
        this.onOk = this.onOk.bind(this);
        this.onCancel = this.onCancel.bind(this);
        this.onParamObjChange = this.onParamObjChange.bind(this);
        this.onCompareTypeObjChange = this.onCompareTypeObjChange.bind(this);
        this.onValueTypeObjChange = this.onValueTypeObjChange.bind(this);
        this.onParamValueObjChange = this.onParamValueObjChange.bind(this);
        this.onParamValueObj4DateChange = this.onParamValueObj4DateChange.bind(this);
        this.getExpsComp = this.getExpsComp.bind(this);
        this.onExpClick = this.onExpClick.bind(this);
        this.onAdd = this.onAdd.bind(this);
        this.onDel = this.onDel.bind(this);
        this.onAnd = this.onAnd.bind(this);
        this.onOr = this.onOr.bind(this);
        this.onSplit = this.onSplit.bind(this);
    }

    render() {
        const {
            visible, loading, settingParams, paramObj, compareTypeObj, valueTypeObj,
            paramValueOptions, paramValueObj, expsObj, selectedExps
        } = this.state;
        const {hpid, ebaseid, wfid} = settingParams;
        const {paramData = {id: '0', name: '请选择参数'}, htmlType, fieldType, isMulti} = paramObj;
        const {compareTypeOptions, compareType} = compareTypeObj;
        const {valueTypeOptions, valueType} = valueTypeObj;
        const {paramValue, paramValueData = {id: '0', name: ''}} = paramValueObj;

        let paramComp = (
            <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@wolwe1`}
                title={getLabel(386382,"请选择")}
                icon="icon-coms-synergism"
                iconBgcolor='#1a57a0'
                type={'synergyParams'}
                modalStyle={{width: 500}}
                isSingle={true}
                dataParams={{type: 'param', ebaseid, wfid}}
                replaceDatas={[paramData]}
                onChange={this.onParamObjChange}
            />
        );
        let compareTypeComp = <div></div>;
        let valueTypeComp = <div></div>;
        let paramValueComp = <div></div>;

        if (paramData.id && paramData.id != '0') {
            compareTypeComp = (
                <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@cr9l1z`}
                    options={compareTypeOptions}
                    value={compareType}
                    onChange={(key) => this.onCompareTypeObjChange(key, getSelectedName(compareTypeOptions, key))}
                />
            );

            valueTypeComp = (
                <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@1ugzw3`}
                    options={valueTypeOptions}
                    value={valueType}
                    onChange={(key) => this.onValueTypeObjChange(key, getSelectedName(valueTypeOptions, key))}
                />
            );

            if (htmlType == '1' || htmlType == '2') { // 单行文本框、多行文本框
                paramValueComp = (
                    <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@nrfdzm`}
                        value={paramValue}
                        onChange={(value) => this.onParamValueObjChange(value, value)}
                    />
                );
            } else if (htmlType == '3') { // 浏览框
                if (valueType == '2') { // 固定值
                    if (fieldType == '2') { // 日期类型
                        paramValueComp = (
                            <WeaDateGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaDateGroup@8simyy`}
                                isMobx={true}
                                datas={DATE_TYPES}
                                value={paramValue.split(',')}
                                onChange={this.onParamValueObj4DateChange}
                            />
                        );
                    } else {
                        paramValueComp = (
                            <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@rh2z19`}
                                type={fieldType}
                                isSingle={!isMulti}
                                replaceDatas={isMulti ? [] : [paramValueData]}
                                onChange={this.onParamValueObjChange}
                            />
                        );
                    }
                } else if (valueType == '3') { // 系统变量
                    paramValueComp = (
                        <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@3s2mgw`}
                            title={getLabel(386382,"请选择")}
                            icon="icon-coms-synergism"
                            iconBgcolor='#1a57a0'
                            type={'synergyParams'}
                            modalStyle={{width: 500}}
                            isSingle={true}
                            dataParams={{type: 'paramvalue', ebaseid: 'sysparam', htmlType, fieldType}}
                            replaceDatas={[paramValueData]}
                            onChange={this.onParamValueObjChange}
                        />
                    );
                }
            } else if (htmlType == '5') { // 单选框
                paramValueComp = (
                    <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@cmdjcu`}
                        options={paramValueOptions}
                        value={paramValue}
                        style={{width: '100px'}}
                        onChange={(key) => this.onParamValueObjChange(key, getSelectedName(paramValueOptions, key))}
                    />
                );
            }

            if (valueType == '6') { // 表单变量
                paramValueComp = (
                    <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@41zgd6`}
                        title={getLabel(386382,"请选择")}
                        icon="icon-coms-synergism"
                        iconBgcolor='#1a57a0'
                        type={'synergyParams'}
                        modalStyle={{width: 500}}
                        isSingle={true}
                        dataParams={{type: 'paramvalue', ebaseid, hpid, htmlType, fieldType}}
                        replaceDatas={[paramValueData]}
                        onChange={this.onParamValueObjChange}
                    />
                );
            }
        }

        return (
            <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@90665s`}
                visible={visible}
                loading={loading}
                title="元素参数设置"
                icon="icon-coms-synergism"
                iconBgcolor='#1a57a0'
                style={{width: 800, height: 400}}
                hasScroll={true}
                buttons={this.getButtons()}
                onCancel={this.onCancel}
            >
                <div className="synergy-setting-designer">
                    <div className="synergy-setting-select">
                        <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@8wb6oo`} gutter={8}>
                            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@busadi`} span={6}>{paramComp}</Col>
                            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@v30wrj`} span={4}>{compareTypeComp}</Col>
                            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@ykv1d2`} span={4}>{valueTypeComp}</Col>
                            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@i882r5`} span={10}>{paramValueComp}</Col>
                        </Row>
                    </div>
                    <div className="synergy-setting-op">
                        <div className="synergy-setting-op-add" title="添加" onClick={this.onAdd}></div>
                        <div className="synergy-setting-op-del" title="删除" onClick={this.onDel}></div>
                        <div className="synergy-setting-op-and" title="添加与关系" onClick={this.onAnd}></div>
                        <div className="synergy-setting-op-or" title="添加或关系" onClick={this.onOr}></div>
                        <div className="synergy-setting-op-split" title="拆分关系" onClick={this.onSplit}></div>
                    </div>
                    <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@872okx`} spinning={loading}>
                        <div className="synergy-setting-preview">
                            {this.getExpsComp(expsObj, selectedExps)}
                        </div>
                    </Spin>
                </div>
            </WeaDialog>
        );
    }

    onShow(params) {
        this.setState({visible: true, loading: true, settingParams: params});

        WeaTools.callApi('/api/portal/synergy/getParams', 'GET', params).then(data => {
            this.setState({loading: false, expsObj: data.expsObj});
        });
    }

    getButtons() {
        let buttons = [];
        buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@rnlob5`} type="primary" onClick={this.onOk}>{getLabel(826, '确定')}</Button>);
        buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@1zbdjk`} type="ghost" onClick={this.onCancel}>{getLabel(31129, '取消')}</Button>);
        return buttons;
    }

    onOk() {
        const {settingParams, expsObj} = this.state;

        WeaTools.callApi('/api/portal/synergy/setParams', 'POST', {
            ...settingParams,
            expsStr: JSON.stringify(expsObj)
        }).then(data => {
        });

        this.onCancel();
    }

    onCancel() {
        this.setState({
            visible: false,
            settingParams: {},
            paramObj: {},
            compareTypeObj: {},
            valueTypeObj: {},
            paramValueOptions: [],
            paramValueObj: {},
            expsObj: {},
            selectedExps: [],
            selectedExpsPKey: ''
        });
    }

    onParamObjChange(ids, names, datas) {
        const {settingParams} = this.state;
        const {stype, pagetype, ispagedeal, ebaseid} = settingParams;
        let {id, fromtype, formid, isbill, htmltype, fieldtype} = datas[0] || {};
        if (fieldtype == '17') {
            fieldtype = '1';
        }
        const isMulti = isMultiBrowserType(fieldtype); // 判断当前字段是否是多选类型

        this.setState({
            paramObj: {
                paramData: datas[0] || {},
                fromType: fromtype,
                formId: formid,
                isBill: isbill,
                paramId: ids,
                paramName: names,
                htmlType: htmltype,
                fieldType: fieldtype,
                isMulti: isMulti
            }
        });

        const compareTypeOptions4 = {key: '4', selected: false, showname: '等于'};
        const compareTypeOptions5 = {key: '5', selected: false, showname: '不等于'};
        const compareTypeOptions6 = {key: '6', selected: false, showname: '包含'};
        const compareTypeOptions7 = {key: '7', selected: false, showname: '不包含'};
        const compareTypeOptions8 = {key: '8', selected: false, showname: '属于'};
        const compareTypeOptions9 = {key: '9', selected: false, showname: '不属于'};

        const valueTypeOption0 = {key: '0', selected: false, showname: '输入值'};
        const valueTypeOption2 = {key: '2', selected: false, showname: '固定值'};
        const valueTypeOption3 = {key: '3', selected: false, showname: '系统变量'};
        const valueTypeOption4 = {key: '4', selected: false, showname: '下拉选择'};
        const valueTypeOption6 = {key: '6', selected: false, showname: '表单变量'};

        // 流程查看处理页和流程表单才有表单变量
        const isNeedFormVar = ebaseid == '8' && ((stype == 'wf' && pagetype == 'operat' && ispagedeal == '1') || stype == 'wf_form');

        if (htmltype == '1' || htmltype == '2') { // 单行文本框、多行文本框
            const compareTypeOptions = [compareTypeOptions4, compareTypeOptions5, compareTypeOptions6, compareTypeOptions7];
            const valueTypeOptions = [valueTypeOption0];
            if (isNeedFormVar) {
                valueTypeOptions.push(valueTypeOption6);
            }

            this.setState({
                compareTypeObj: {
                    compareTypeOptions: compareTypeOptions,
                    compareType: compareTypeOptions[0].key,
                    compareName: compareTypeOptions[0].showname
                },
                valueTypeObj: {
                    valueTypeOptions: valueTypeOptions,
                    valueType: valueTypeOptions[0].key,
                    valueTypeName: valueTypeOptions[0].showname
                },
                paramValueOptions: [],
                paramValueObj: {
                    paramValue: '',
                    paramValueName: ''
                }
            });
        } else if (htmltype == '3') { // 浏览框
            const compareTypeOptions = isMulti ? [compareTypeOptions6, compareTypeOptions7] : [compareTypeOptions8, compareTypeOptions9];
            const valueTypeOptions = [valueTypeOption2, valueTypeOption3];
            if (isNeedFormVar) {
                valueTypeOptions.push(valueTypeOption6);
            }

            this.setState({
                compareTypeObj: {
                    compareTypeOptions: compareTypeOptions,
                    compareType: compareTypeOptions[0].key,
                    compareName: compareTypeOptions[0].showname
                },
                valueTypeObj: {
                    valueTypeOptions: valueTypeOptions,
                    valueType: valueTypeOptions[0].key,
                    valueTypeName: valueTypeOptions[0].showname
                },
                paramValueOptions: [],
                paramValueObj: {
                    paramValue: fieldtype == '2' ? '0' : '', // fieldtype == '2' 为日期类型
                    paramValueName: fieldtype == '2' ? getDateTypeName('0') : ''
                }
            });
        } else if (htmltype == '5') { // 单选框
            const compareTypeOptions = [compareTypeOptions4, compareTypeOptions5];
            const valueTypeOptions = [valueTypeOption4];
            if (isNeedFormVar) {
                valueTypeOptions.push(valueTypeOption6);
            }

            WeaTools.callApi('/api/portal/synergy/getWfSelectItems', 'GET', {
                fieldtype: fieldtype,
                fieldid: id
            }).then(data => {
                const selectItems = data.data || [];

                let paramValueOptions = [];
                for (let i = 0, len = selectItems.length; i < len; i++) {
                    paramValueOptions.push({key: selectItems[i].value, selected: false, showname: selectItems[i].name});
                }

                this.setState({
                    compareTypeObj: {
                        compareTypeOptions: compareTypeOptions,
                        compareType: compareTypeOptions[0].key,
                        compareName: compareTypeOptions[0].showname
                    },
                    valueTypeObj: {
                        valueTypeOptions: valueTypeOptions,
                        valueType: valueTypeOptions[0].key,
                        valueTypeName: valueTypeOptions[0].showname
                    },
                    paramValueOptions: paramValueOptions,
                    paramValueObj: {
                        paramValue: paramValueOptions.length ? paramValueOptions[0].key : '',
                        paramValueName: paramValueOptions.length ? paramValueOptions[0].showname : ''
                    }
                });
            });
        }
    }

    onCompareTypeObjChange(type, name) {
        const {compareTypeObj} = this.state;
        this.setState({compareTypeObj: {...compareTypeObj, compareType: type, compareName: name}});
    }

    onValueTypeObjChange(type, name) {
        const {paramObj, valueTypeObj, paramValueOptions} = this.state;
        const {htmlType, fieldType} = paramObj;

        let paramValueObj = {};
        if (htmlType == '3') { // 浏览框
            if (type == '2' && fieldType == '2') { // 固定值，并且为日期类型
                paramValueObj = {
                    paramValue: '0',
                    paramValueName: getDateTypeName('0')
                }
            }
        } else if (htmlType == '5') { // 单选框
            if (type == '4') { // 下拉选择
                paramValueObj = {
                    paramValue: paramValueOptions.length ? paramValueOptions[0].key : '',
                    paramValueName: paramValueOptions.length ? paramValueOptions[0].showname : ''
                }
            }
        }

        this.setState({
            valueTypeObj: {...valueTypeObj, valueType: type, valueTypeName: name},
            paramValueObj: paramValueObj
        });
    }

    onParamValueObjChange(ids, names, datas) {
        const {valueTypeObj, paramValueObj} = this.state;
        const {valueType} = valueTypeObj;

        if (valueType == '6' && datas && datas.length) { // 表单变量
            const {formid, isbill, id} = datas[0];
            this.setState({paramValueObj: {...paramValueObj, paramValue: ids, paramValueName: names, paramValueData: datas[0], filterFormId: formid, filterIsBill: isbill, filterId: id}});
        } else {
            if (datas && datas.length) {
                this.setState({paramValueObj: {...paramValueObj, paramValue: ids, paramValueName: names, paramValueData: datas[0]}});
            } else {
                this.setState({paramValueObj: {...paramValueObj, paramValue: ids, paramValueName: names}});
            }
        }
    }

    onParamValueObj4DateChange(value) {
        const {paramValueObj} = this.state;
        const [dateType, startDate, endDate] = value;

        let paramValue = dateType;
        let paramValueName = getDateTypeName(dateType);

        if (dateType == '6') { // 指定日期范围
            paramValue = value.join(',');
            paramValueName += '(' + startDate + ' 至 ' + endDate + ')';
        }

        this.setState({paramValueObj: {...paramValueObj, paramValue: paramValue, paramValueName: paramValueName}});
    }

    getExpsComp(expsObj, selectedExps) {
        const {relation = '1', expressions = []} = expsObj;

        let expsComp = <div></div>;
        if (expressions && expressions.length) {
            expsComp = (
                <div className="synergy-setting-exps">
                    <div className="synergy-setting-relation">
                        {relation == '1' ? 'AND' : 'OR'}
                    </div>
                    <div className="synergy-setting-line"></div>
                    {
                        expressions.map((item) => {
                            let selected = false;
                            for (let i = 0, len = selectedExps.length; i < len; i++) {
                                if (selectedExps[i].key == item.key) {
                                    selected = true;
                                }
                            }
                            const style = {border: selected ? '2px dashed #17d68c' : '2px solid #fff'};

                            if (item.relation == 0 || item.relation == 1) {
                                return (
                                    <div key={item.key} className="synergy-setting-exps-child" style={style} onClick={(e) => this.onExpClick(e, selected, item)}>
                                        {this.getExpsComp(item, selectedExps)}
                                    </div>
                                );
                            } else {
                                return (
                                    <div key={item.key} className="synergy-setting-exp">
                                        <span style={style} onClick={(e) => this.onExpClick(e, selected, item)}>
                                            {item.paramName} {item.compareName} {item.paramValueName}
                                        </span>
                                    </div>
                                );
                            }
                        })
                    }
                </div>
            );
        }

        return expsComp;
    }

    onExpClick(e, selected, exp) {
        e.stopPropagation();

        let {selectedExps, selectedExpsPKey} = this.state;

        if (selected) {
            let _selectedExps = [];
            for (let i = 0, len = selectedExps.length; i < len; i++) {
                if (selectedExps[i].key != exp.key) {
                    _selectedExps.push(selectedExps[i]);
                }
            }
            selectedExps = _selectedExps;
        } else {
            if (selectedExpsPKey && selectedExpsPKey != exp.parentKey) {
                selectedExps = [];
            }

            selectedExps.push(exp);
        }

        this.setState({selectedExps: selectedExps, selectedExpsPKey: exp.parentKey});
    }

    onAdd() {
        const {paramObj, compareTypeObj, valueTypeObj, paramValueObj} = this.state;
        const {fromType, formId, isBill, paramId, paramName, fieldType} = paramObj;
        const {compareType, compareName} = compareTypeObj;
        const {valueType} = valueTypeObj;
        const {paramValue, paramValueName, filterFormId, filterIsBill, filterId} = paramValueObj;

        if (!paramId || paramId == '0') {
            message.warning('请选择参数！');
        } else if (!paramValue) {
            message.warning('请选择参数值！');
        } else {
            let {expsObj} = this.state;
            const curTime = new Date().getTime();

            const expression = {
                key: 'exp_' + curTime,
                parentKey: expsObj.key || 'exps_' + curTime,
                id: 'exp_' + curTime,
                variableId: 'exp_' + curTime,
                fromType: fromType,
                formId: formId,
                isBill: isBill,
                paramId: paramId,
                paramName: paramName,
                paramType: valueType == '0' ? '0' : '1',
                fieldType: fieldType,
                compareType: compareType,
                compareName: compareName,
                valueType: valueType,
                paramValue: paramValue,
                paramValueName: paramValueName,
                valueVariableId: fieldType,
                filterFormId: filterFormId,
                filterIsBill: filterIsBill,
                filterId: filterId
            };

            let {expressions = []} = expsObj;
            if (expressions && expressions.length) {
                expressions.push(expression);
            } else {
                expsObj = {key: 'exps_' + curTime, parentKey: 'exps_0', relation: '1', expressions: [expression]};
            }

            this.setState({expsObj: expsObj});
        }
    }

    onDel() {
        let {expsObj, selectedExps, selectedExpsPKey} = this.state;

        if (selectedExps && selectedExps.length) {
            this._onDel(expsObj, selectedExps, selectedExpsPKey, false);
            this.setState({expsObj: expsObj, selectedExps: [], selectedExpsPKey: ''});
        } else {
            message.warning('请选择需要删除的条件！');
        }
    }

    _onDel(expsObj, selectedExps, selectedExpsPKey, flag) {
        let {key, expressions = []} = expsObj;

        if (key == selectedExpsPKey) {
            let _expressions = [];
            for (let i = 0, len = expressions.length; i < len; i++) {
                let count = 0;
                for (let j = 0, len2 = selectedExps.length; j < len2; j++) {
                    if (expressions[i].key == selectedExps[j].key) {
                        count++;
                    }
                }
                if (count == 0) {
                    _expressions.push(expressions[i]);
                }
            }
            expsObj.expressions = _expressions;
        } else {
            let _expressions = [];
            for (let i = 0, len = expressions.length; i < len; i++) {
                let _expsObj = expressions[i];

                if (_expsObj.expressions) {
                    this._onDel(_expsObj, selectedExps, selectedExpsPKey, flag);
                    if (flag || (_expsObj.expressions && _expsObj.expressions.length)) {
                        _expressions.push(_expsObj);
                    }
                } else {
                    _expressions.push(_expsObj);
                }
            }
            expsObj.expressions = _expressions;
        }
    }

    onAnd() {
        this.onAndOr('1');
    }

    onOr() {
        this.onAndOr('0');
    }

    onAndOr(relation) {
        let {expsObj, selectedExps, selectedExpsPKey} = this.state;

        if (selectedExps && selectedExps.length) {
            this._onDel(expsObj, selectedExps, selectedExpsPKey, true);

            const curTime = new Date().getTime();
            for (let i = 0, len = selectedExps.length; i < len; i++) {
                selectedExps[i].parentKey = 'exps_' + curTime;
            }
            const exps = {key: 'exps_' + curTime, parentKey: selectedExpsPKey, relation: relation, expressions: selectedExps};
            this._onAndOr(expsObj, selectedExpsPKey, exps);
            this.setState({expsObj: expsObj, selectedExps: [], selectedExpsPKey: ''});
        }
    }

    _onAndOr(expsObj, selectedExpsPKey, exps) {
        let {key, expressions = []} = expsObj;

        if (key == selectedExpsPKey) {
            expressions.push(exps);
            expsObj.expressions = expressions;
        } else {
            for (let i = 0, len = expressions.length; i < len; i++) {
                let _expsObj = expressions[i];
                if (_expsObj.expressions) {
                    this._onAndOr(_expsObj, selectedExpsPKey, exps);
                }
            }
        }
    }

    onSplit() {
        let {expsObj, selectedExps, selectedExpsPKey} = this.state;
        for (let i = 0, len = selectedExps.length; i < len; i++) {
            let {key, expressions} = selectedExps[i];
            if (expressions && expressions.length) {
                for (let j = 0, len2 = expressions.length; j < len2; j++) {
                    expressions[j].parentKey = selectedExpsPKey;
                }
                this._onSplit(expsObj, key, expressions);
            }
        }
        this.setState({expsObj: expsObj, selectedExps: [], selectedExpsPKey: ''});
    }

    _onSplit(expsObj, selectedExpsKey, exps) {
        let {expressions = []} = expsObj;

        for (let i = 0, len = expressions.length; i < len; i++) {
            if (expressions[i].key == selectedExpsKey) {
                expressions.splice(i, 1, ...exps);
                break;
            } else if (expressions[i].expressions) {
                this._onSplit(expressions[i], selectedExpsKey, exps);
            }
        }
    }
}

export default SynergySetting4Designer;
